package services

import (
	"context"
	"wxapi/internal/svc"
	"wxapi/models"

	"github.com/shopspring/decimal"
)

func CreateUser(ctx context.Context, svcCtx *svc.ServiceContext, openId, unionId, nickname, avatar, country, province, city string, gender int64) *models.User {
	user := &models.User{}

	svcCtx.Mysql.Model(&models.User{}).Preload("UserInfo").Where("open_id = ? AND union_id = ?", openId, unionId).Find(&user)
	if user.ID != 0 {
		user.Nickname = nickname
		user.Avatar = avatar
		svcCtx.Mysql.Save(user)
	} else {
		user.OpenId = openId
		user.UnionId = unionId
		user.Nickname = nickname
		user.Avatar = avatar
		user.Gender = gender
		user.Country = country
		user.Province = province
		user.City = city
		user.UserInfo = &models.UserInfo{
			UserName: user.Nickname,
			Gender:   gender,
		}
		user.UserWallet = &models.UserWallet{
			Money: decimal.NewFromFloat(0.0),
			Point: int64(0),
		}

		svcCtx.Mysql.Create(user)
	}
	return user
}

func GetUserById(ctx context.Context, svcCtx *svc.ServiceContext, userId int64) (*models.User, error) {
	user := &models.User{}
	svcCtx.Mysql.Model(&models.User{}).Preload("UserInfo").Preload("Member").Preload("Member.Level").Preload("Member.Level.Discount").Where("id = ?", userId).Find(&user)
	if user.ID == 0 {
		return nil, nil
	}
	return user, nil
}
